package com.qf.sys.controller;

import com.qf.sys.param.LoginParam;
import com.qf.utils.AliSmsUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.qf.sys.service.SysUserService;
import com.qf.common.R;
import com.qf.entity.sys.*;
import com.qf.utils.RedisUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户管理")
public class SysUserController {
    @Autowired
    private  RedisUtil redisUtil;
    @Autowired
    private  SysUserService sysUserService;
    @PostMapping("/login")
    public R login(@RequestBody LoginParam loginParam, HttpSession session){
        String token = sysUserService.login(loginParam);
        session.setAttribute("token", token);
        //生成token
        //本例使用uuid作为token
        return R.ok(token);
    }

    @GetMapping("/info")
    public R info(HttpSession session){
        String token = (String) session.getAttribute("token");
        return R.ok(token);
    }

    @GetMapping("/sendsms")
    public R sendsms(String phone){
        //生成验证码
        //String code = UUID.randomUUID().toString().substring(0, 4);
        //String code = String.valueOf(new Random().nextInt(9999) + 1000);
        AliSmsUtils.sendSms("千锋互联",

                        "SMS_296820879", phone, "1267");
        //发送验证码

        //将验证码保存到redis中
        redisUtil.setCacheObject(phone, "1267", 5, TimeUnit.MINUTES);
        return R.ok(null);
    }
    @PostMapping("/logout")
    public R logout(HttpSession session, HttpServletRequest request){
        session.invalidate();//清除session
        String token = request.getHeader("Authorization");
        redisUtil.deleteObject(token);
        return R.ok(null);
    }

}
